{% extends "base.html" %}

{% block title %}图片库{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <!-- 页面标题 -->
        <div class="col-12 mb-4">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h3 class="mb-1">
                                <i class="bi bi-images me-2"></i>图片库
                            </h3>
                            <p class="text-muted mb-0">浏览和查看所有图片</p>
                        </div>
                        <div>
                            <button class="btn btn-outline-primary" onclick="refreshImages()">
                                <i class="bi bi-arrow-clockwise me-1"></i>刷新
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <div class="col-12 mb-4">
            <div class="card">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="input-group">
                                <span class="input-group-text">
                                    <i class="bi bi-search"></i>
                                </span>
                                <input type="text" class="form-control" id="searchInput" placeholder="搜索图片名称...">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <select class="form-control" id="sortSelect">
                                <option value="time_desc">按时间降序</option>
                                <option value="time_asc">按时间升序</option>
                                <option value="name_asc">按名称升序</option>
                                <option value="size_desc">按大小降序</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-control" id="viewSelect">
                                <option value="grid">网格视图</option>
                                <option value="list">列表视图</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图片内容区域 -->
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <!-- 加载状态 -->
                    <div id="loadingSpinner" class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2 text-muted">加载图片中...</p>
                    </div>

                    <!-- 无图片状态 -->
                    <div id="noImages" class="text-center py-5" style="display: none;">
                        <i class="bi bi-images" style="font-size: 4rem; color: #6b7280;"></i>
                        <h4 class="mt-3 text-muted">暂无图片</h4>
                        <p class="text-muted">还没有上传任何图片</p>
                    </div>

                    <!-- 网格视图 -->
                    <div id="gridView" class="row g-3" style="display: none;">
                        <!-- 图片卡片将在这里动态生成 -->
                    </div>

                    <!-- 列表视图 -->
                    <div id="listView" style="display: none;">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>预览</th>
                                        <th>文件名</th>
                                        <th>大小</th>
                                        <th>尺寸</th>
                                        <th>上传时间</th>
                                        <th>上传者</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="listViewBody">
                                    <!-- 表格行将在这里动态生成 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 图片详情模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">图片详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-8">
                        <div class="text-center">
                            <img id="modalImage" class="img-fluid rounded shadow" style="max-height: 500px; max-width: 100%;">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <h6 class="border-bottom pb-2 mb-3">图片信息</h6>
                        <table class="table table-sm table-borderless">
                            <tr>
                                <td class="text-muted" style="width: 80px;"><strong>文件名:</strong></td>
                                <td id="modalFilename" class="text-break">-</td>
                            </tr>
                            <tr>
                                <td class="text-muted"><strong>原始名称:</strong></td>
                                <td id="modalOriginalName" class="text-break">-</td>
                            </tr>
                            <tr>
                                <td class="text-muted"><strong>文件大小:</strong></td>
                                <td id="modalSize">-</td>
                            </tr>
                            <tr>
                                <td class="text-muted"><strong>图片尺寸:</strong></td>
                                <td id="modalDimensions">-</td>
                            </tr>
                            <tr>
                                <td class="text-muted"><strong>上传时间:</strong></td>
                                <td id="modalUploadTime">-</td>
                            </tr>
                            <tr>
                                <td class="text-muted"><strong>上传者:</strong></td>
                                <td id="modalUploader">-</td>
                            </tr>
                        </table>
                        
                        <h6 class="border-bottom pb-2 mb-3 mt-4">图片链接</h6>
                        <div class="input-group mb-3">
                            <input type="text" class="form-control form-control-sm" id="imageUrl" readonly>
                            <button class="btn btn-outline-primary btn-sm" onclick="copyUrl()">
                                <i class="bi bi-clipboard"></i>
                            </button>
                        </div>
                        
                        <div class="d-grid gap-2">
                            <button class="btn btn-primary btn-sm" onclick="openImageInNewTab()">
                                <i class="bi bi-box-arrow-up-right me-1"></i>在新标签页打开
                            </button>
                            <button class="btn btn-outline-secondary btn-sm" onclick="downloadImage()">
                                <i class="bi bi-download me-1"></i>下载图片
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 图片轮播模态框 -->
<div class="modal fade" id="carouselModal" tabindex="-1">
    <div class="modal-dialog modal-fullscreen">
        <div class="modal-content bg-dark">
            <div class="modal-header border-0">
                <h5 class="modal-title text-white">图片浏览</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
                <div id="imageCarousel" class="carousel slide h-100" data-bs-ride="false">
                    <div class="carousel-inner h-100" id="carouselInner">
                        <!-- 轮播项将在这里动态生成 -->
                    </div>
                    <button class="carousel-control-prev" type="button" data-bs-target="#imageCarousel" data-bs-slide="prev">
                        <span class="carousel-control-prev-icon"></span>
                    </button>
                    <button class="carousel-control-next" type="button" data-bs-target="#imageCarousel" data-bs-slide="next">
                        <span class="carousel-control-next-icon"></span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentImages = [];
let filteredImages = [];
let currentViewMode = 'grid';

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadImages();
    initializeFilters();
});

// 加载图片列表
async function loadImages() {
    showLoading();
    
    try {
        const response = await fetch('/api/images');
        const images = await response.json();
        
        currentImages = images;
        filteredImages = [...images];
        
        if (images.length === 0) {
            showNoImages();
        } else {
            renderImages();
        }
    } catch (error) {
        console.error('Failed to load images:', error);
        showToast('加载图片失败', 'error');
        showNoImages();
    }
}

// 显示加载状态
function showLoading() {
    document.getElementById('loadingSpinner').style.display = 'block';
    document.getElementById('noImages').style.display = 'none';
    document.getElementById('gridView').style.display = 'none';
    document.getElementById('listView').style.display = 'none';
}

// 显示无图片状态
function showNoImages() {
    document.getElementById('loadingSpinner').style.display = 'none';
    document.getElementById('noImages').style.display = 'block';
    document.getElementById('gridView').style.display = 'none';
    document.getElementById('listView').style.display = 'none';
}

// 渲染图片
function renderImages() {
    document.getElementById('loadingSpinner').style.display = 'none';
    document.getElementById('noImages').style.display = 'none';
    
    if (currentViewMode === 'grid') {
        renderGridView();
        document.getElementById('gridView').style.display = 'flex';
        document.getElementById('listView').style.display = 'none';
    } else {
        renderListView();
        document.getElementById('gridView').style.display = 'none';
        document.getElementById('listView').style.display = 'block';
    }
}

// 渲染网格视图
function renderGridView() {
    const grid = document.getElementById('gridView');
    grid.innerHTML = '';
    
    filteredImages.forEach((image, index) => {
        const col = document.createElement('div');
        col.className = 'col-lg-3 col-md-4 col-sm-6 col-12';
        
        col.innerHTML = `
            <div class="image-card h-100">
                <div class="position-relative">
                    <img src="/thumbnails/${image.thumbnail}" 
                         class="image-thumbnail" 
                         alt="${image.original_name}"
                         style="cursor: pointer;"
                         onclick="showImageModal('${image.id}')">
                    <div class="position-absolute top-0 end-0 m-2">
                        <button class="btn btn-light btn-sm opacity-75" onclick="showImageCarousel(${index})">
                            <i class="bi bi-arrows-fullscreen"></i>
                        </button>
                    </div>
                </div>
                <div class="p-3">
                    <h6 class="mb-1 text-truncate" title="${image.original_name}">${image.original_name}</h6>
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">${formatFileSize(image.size)}</small>
                        <small class="text-muted">${image.width} × ${image.height}</small>
                    </div>
                    <small class="text-muted d-block mt-1">${formatDate(image.upload_time)}</small>
                    <div class="mt-2 d-flex gap-1">
                        <button class="btn btn-outline-primary btn-sm flex-fill" onclick="showImageModal('${image.id}')">
                            <i class="bi bi-eye me-1"></i>详情
                        </button>
                        <button class="btn btn-outline-secondary btn-sm" onclick="copyImageUrl('${image.filename}')">
                            <i class="bi bi-clipboard"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        grid.appendChild(col);
    });
}

// 渲染列表视图
function renderListView() {
    const tbody = document.getElementById('listViewBody');
    tbody.innerHTML = '';
    
    filteredImages.forEach((image, index) => {
        const row = document.createElement('tr');
        row.style.cursor = 'pointer';
        row.onclick = () => showImageModal(image.id);
        
        row.innerHTML = `
            <td>
                <img src="/thumbnails/${image.thumbnail}" 
                     class="rounded" 
                     style="width: 60px; height: 60px; object-fit: cover;">
            </td>
            <td>
                <div class="text-truncate" style="max-width: 200px;" title="${image.original_name}">
                    ${image.original_name}
                </div>
                <small class="text-muted">${image.filename}</small>
            </td>
            <td>${formatFileSize(image.size)}</td>
            <td>${image.width} × ${image.height}</td>
            <td>
                <div>${formatDate(image.upload_time)}</div>
                <small class="text-muted">${image.uploader}</small>
            </td>
            <td>
                <span class="badge bg-secondary">${image.uploader}</span>
            </td>
            <td>
                <div class="btn-group" role="group">
                    <button class="btn btn-outline-primary btn-sm" onclick="event.stopPropagation(); showImageModal('${image.id}')">
                        <i class="bi bi-eye"></i>
                    </button>
                    <button class="btn btn-outline-secondary btn-sm" onclick="event.stopPropagation(); copyImageUrl('${image.filename}')">
                        <i class="bi bi-clipboard"></i>
                    </button>
                    <button class="btn btn-outline-success btn-sm" onclick="event.stopPropagation(); showImageCarousel(${index})">
                        <i class="bi bi-arrows-fullscreen"></i>
                    </button>
                </div>
            </td>
        `;
        
        tbody.appendChild(row);
    });
}

// 显示图片详情模态框
function showImageModal(imageId) {
    const image = currentImages.find(img => img.id === imageId);
    if (!image) return;
    
    document.getElementById('modalImage').src = `/uploads/${image.filename}`;
    document.getElementById('modalFilename').textContent = image.filename;
    document.getElementById('modalOriginalName').textContent = image.original_name;
    document.getElementById('modalSize').textContent = formatFileSize(image.size);
    document.getElementById('modalDimensions').textContent = `${image.width} × ${image.height}`;
    document.getElementById('modalUploadTime').textContent = formatDate(image.upload_time);
    document.getElementById('modalUploader').textContent = image.uploader;
    document.getElementById('imageUrl').value = `${window.location.origin}/uploads/${image.filename}`;
    
    new bootstrap.Modal(document.getElementById('imageModal')).show();
}

// 显示图片轮播
function showImageCarousel(startIndex = 0) {
    const carouselInner = document.getElementById('carouselInner');
    carouselInner.innerHTML = '';
    
    filteredImages.forEach((image, index) => {
        const item = document.createElement('div');
        item.className = `carousel-item ${index === startIndex ? 'active' : ''}`;
        
        item.innerHTML = `
            <div class="d-flex align-items-center justify-content-center h-100">
                <img src="/uploads/${image.filename}" 
                     class="d-block img-fluid" 
                     style="max-height: 90vh; max-width: 90vw; object-fit: contain;">
            </div>
            <div class="carousel-caption">
                <h5>${image.original_name}</h5>
                <p>${formatFileSize(image.size)} • ${image.width} × ${image.height}</p>
            </div>
        `;
        
        carouselInner.appendChild(item);
    });
    
    new bootstrap.Modal(document.getElementById('carouselModal')).show();
}

// 复制图片链接
function copyImageUrl(filename) {
    const url = `${window.location.origin}/uploads/${filename}`;
    navigator.clipboard.writeText(url).then(() => {
        showToast('链接已复制到剪贴板', 'success');
    });
}

// 复制当前模态框中的链接
function copyUrl() {
    const urlInput = document.getElementById('imageUrl');
    urlInput.select();
    navigator.clipboard.writeText(urlInput.value).then(() => {
        showToast('链接已复制到剪贴板', 'success');
    });
}

// 在新标签页打开图片
function openImageInNewTab() {
    const url = document.getElementById('imageUrl').value;
    window.open(url, '_blank');
}

// 下载图片
function downloadImage() {
    const url = document.getElementById('imageUrl').value;
    const filename = document.getElementById('modalOriginalName').textContent;
    
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
}

// 刷新图片列表
function refreshImages() {
    loadImages();
}

// 初始化过滤器
function initializeFilters() {
    const searchInput = document.getElementById('searchInput');
    const sortSelect = document.getElementById('sortSelect');
    const viewSelect = document.getElementById('viewSelect');
    
    searchInput.addEventListener('input', filterAndSortImages);
    sortSelect.addEventListener('change', filterAndSortImages);
    viewSelect.addEventListener('change', function() {
        currentViewMode = this.value;
        if (filteredImages.length > 0) {
            renderImages();
        }
    });
}

// 过滤和排序图片
function filterAndSortImages() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    const sortType = document.getElementById('sortSelect').value;
    
    // 过滤
    filteredImages = currentImages.filter(image => 
        image.original_name.toLowerCase().includes(searchTerm) ||
        image.filename.toLowerCase().includes(searchTerm)
    );
    
    // 排序
    switch (sortType) {
        case 'time_asc':
            filteredImages.sort((a, b) => new Date(a.upload_time) - new Date(b.upload_time));
            break;
        case 'time_desc':
            filteredImages.sort((a, b) => new Date(b.upload_time) - new Date(a.upload_time));
            break;
        case 'name_asc':
            filteredImages.sort((a, b) => a.original_name.localeCompare(b.original_name));
            break;
        case 'size_desc':
            filteredImages.sort((a, b) => b.size - a.size);
            break;
    }
    
    if (filteredImages.length === 0 && searchTerm) {
        showNoImages();
    } else {
        renderImages();
    }
}
</script>
{% endblock %}
